<template>
  <div class="page-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>我的订单</span>
        </div>
      </template>
      <el-table
        :data="orders"
        style="width: 100%"
        border
        class="order-table"
        stripe
      >
        <el-table-column prop="id" label="订单ID" width="120" min-width="100" />
        <el-table-column prop="productName" label="商品名称" width="280" min-width="220" />
        <el-table-column prop="quantity" label="数量" width="120" min-width="80" />
        <el-table-column prop="payAmount" label="支付金额" width="120" min-width="120">
          <template #default="scope">
            ¥{{ scope.row.payAmount ? scope.row.payAmount.toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120" min-width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ formatOrderStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="250" min-width="160" />
        <el-table-column label="操作" width="250" min-width="200">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === 0"
              type="primary"
              size="small"
              @click="handlePayOrder(scope.row.id)"
            >
              继续支付
            </el-button>
            <el-button
              v-if="scope.row.status === 0"
              type="danger"
              size="small"
              @click="handleCancelOrder(scope.row.id)"
            >
              取消订单
            </el-button>
            <el-button
              v-if="[1, 2, 3].includes(scope.row.status)"
              type="warning"
              size="small"
              @click="handleRefundOrder(scope.row.id)"
            >
              申请退款
            </el-button>
            <el-button
              v-if="scope.row.status === 3"
              :type="scope.row.evaluated ? 'success' : 'warning'"
              size="small"
              :disabled="scope.row.evaluated"
              @click="!scope.row.evaluated && openEvaluationDialog(scope.row.orderItemId)"
            >
              {{ scope.row.evaluated ? '已评价' : '评价' }}
            </el-button>
            <el-button
              v-if="scope.row.status === 4"
              type="danger"
              size="small"
              @click="handleDeleteOrder(scope.row.id)"
            >
              删除订单
            </el-button>

            <el-button
              v-if="scope.row.status === 5"
              type="danger"
              size="small"
              :disabled="warning"
            >
              退款中
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="fetchOrders"
          @size-change="fetchOrders"
          class="pagination"
        />
      </div>
    </el-card>

    <el-dialog v-model="showEvalDialog" title="评价商品" width="600px" append-to-body>
      <div class="eval-dialog-body">
        <el-rate v-model="evalForm.score" :max="5" allow-half class="eval-rate" />
        <el-input
          v-model="evalForm.content"
          type="textarea"
          maxlength="500"
          show-word-limit
          placeholder="请分享您的使用体验（限500字）"
          rows="5"
          class="eval-textarea"
        />
        <el-upload
          action="/api/upload/avatar"
          list-type="picture-card"
          :limit="5"
          :on-success="handleUploadSuccess"
          :on-remove="handleUploadRemove"
          :file-list="fileList"
          :before-upload="beforeUpload"
          class="eval-upload"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </div>
      <template #footer>
        <el-button @click="showEvalDialog = false">取消</el-button>
        <el-button type="primary" @click="submitEvaluation">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElRate, ElDialog, ElInput, ElUpload, ElIcon } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getOrdersService, payOrderService, cancelOrderService, refundOrderService, deleteOrderService, submitEvaluationService } from '@/api/user'
import { useUserInfoStore } from '../../stores/userInfo'

const router = useRouter()
const userInfoStore = useUserInfoStore()
const orders = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)

const fetchOrders = async () => {
  loading.value = true
  try {
    const res = await getOrdersService(currentPage.value, pageSize.value, userInfoStore.userInfo.id)
    console.log(res)
    orders.value = res.data.data.data.records.map(order => ({
      ...order,
      orderSn: order.orderSn || ''
    }))
    total.value = res.data.data.data.records.length 
  } catch (error) {
    ElMessage.error('获取订单失败')
  } finally {
    loading.value = false
  }
}

const handlePayOrder = async (orderId) => {
  try {
    const order = orders.value.find(o => o.id === orderId)
    if (!order || !order.orderSn) {
      ElMessage.error('订单编号不可用')
      return
    }
    await ElMessageBox.confirm('确认支付订单？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    // await payOrderService(orderId)
    router.push({ path: '/pay/choose', query: { orderSn: order.orderSn } })
    // ElMessage.success('支付成功')
    fetchOrders()
  } catch (error) {
    ElMessage.error('支付失败：' + (error.response?.data?.message || error.message))
  }
}

const handleCancelOrder = async (operationId) => {
  try {
    await ElMessageBox.confirm('确认取消订单？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await cancelOrderService(operationId)
    ElMessage.success('订单已取消')
    fetchOrders()
  } catch (error) {
    ElMessage.error('取消订单失败')
  }
}

const handleRefundOrder = async (orderId) => {
  try {
    await ElMessageBox.confirm('确认申请退款？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const res = await refundOrderService(orderId)
    console.log(res)
    ElMessage.success('退款申请已提交')
    fetchOrders()
  } catch (error) {
    ElMessage.error('退款申请失败')
  }
}

const showEvalDialog = ref(false)
const evalForm = ref({ content: '', score: 5, images: [] })
const fileList = ref([])
const currentOrderItemId = ref(null)

const openEvaluationDialog = (orderItemId) => {
  currentOrderItemId.value = orderItemId
  evalForm.value = { content: '', score: 5, images: [] }
  fileList.value = []
  showEvalDialog.value = true
}

const beforeUpload = (file) => {
  const isImg = file.type.startsWith('image/')
  if (!isImg) ElMessage.error('仅支持图片格式')
  return isImg
}

const handleUploadSuccess = (response, file) => {
  if (response.url) {
    evalForm.value.images.push(response.url)
    fileList.value.push({ name: file.name, url: response.url })
  }
}

const handleUploadRemove = (file) => {
  evalForm.value.images = evalForm.value.images.filter((url) => url !== file.url)
}

const submitEvaluation = async () => {
  if (!evalForm.value.content.trim()) {
    ElMessage.error('评价内容不能为空')
    return
  }
  try {
    await submitEvaluationService(currentOrderItemId.value, {
      content: evalForm.value.content.trim(),
      score: evalForm.value.score,
      images: (evalForm.value.images || []).join(',')
    })
    ElMessage.success('评价提交成功')
    showEvalDialog.value = false
    fetchOrders()
  } catch (error) {
    ElMessage.error('评价提交失败：' + (error.response?.data?.message || error.message))
  }
}

const handleDeleteOrder = async (orderId) => {
  try {
    await ElMessageBox.confirm('确认删除订单？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteOrderService(orderId)
    ElMessage.success('订单已删除')
    fetchOrders()
  } catch (error) {
    ElMessage.error('删除订单失败')
  }
}

const formatOrderStatus = (status) => {
  switch (status) {
    case 0: return '待支付'
    case 1: return '待发货'
    case 2: return '已发货'
    case 3: return '已完成'
    case 4: return '已取消'
    case 5: return '待退款'
    case 6: return '已退款'
    case 7: return '退款失败'
    default: return '未知状态'
  }
}

const getStatusTagType = (status) => {
  switch (status) {
    case 0: return 'warning'
    case 1: return 'info'
    case 2: return 'primary'
    case 3: return 'success'
    case 4: return 'danger'
    default: return 'info'
  }
}

fetchOrders()
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 9vh;
  padding: 24px;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.box-card {
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  background-color: #fff;
  padding: 20px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.card-header {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  padding: 16px 24px;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 20px;
}

.order-table {
  flex: 1;
  max-height: calc(100vh - 220px); /* 动态计算高度，留出卡片头部和分页空间 */
  overflow-y: auto;
}

/* 优化表格单元格内边距 */
:deep(.el-table__cell) {
  padding: 12px 8px;
  font-size: 14px;
  line-height: 1.5;
}

/* 自定义滚动条 */
.order-table::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.order-table::-webkit-scrollbar-thumb {
  background-color: #c0c4cc;
  border-radius: 4px;
}

.order-table::-webkit-scrollbar-track {
  background-color: #f5f5f5;
  border-radius: 4px;
}

.pagination-container {
  padding: 20px 24px;
  margin-top: 20px;
  background-color: #fff;
  text-align: center;
  min-height: 60px; /* 确保有足够高度 */
  visibility: visible !important; /* 强制可见 */
}

.pagination {
  display: inline-flex !important; /* 强制显示 */
}

.eval-dialog-body {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 24px;
}

.eval-rate {
  font-size: 16px;
}

.eval-textarea {
  font-size: 14px;
  line-height: 1.5;
}

.eval-upload {
  margin-top: 10px;
}

@media (max-width: 768px) {
  .page-container {
    padding: 16px;
  }

  .box-card {
    padding: 16px;
  }

  .card-header {
    font-size: 18px;
    padding: 12px 16px;
    margin-bottom: 16px;
  }

  .order-table {
    max-height: calc(100vh - 200px);
  }

  .pagination-container {
    padding: 16px;
    margin-top: 16px;
  }

  .eval-dialog-body {
    padding: 16px;
    gap: 16px;
  }
}
</style>